const app = getApp();

Page({
  data: {
    posts: [],
    petTypes: ['全部宠物', '狗狗', '猫咪', '兔子', '其他'],
    petTypeIndex: 0,
    loading: false,
    noMore: false,
    searchText: '',
    page: 1
  },

  onLoad() {
    this.loadPosts();
  },

  onShow() {
    this.loadPosts();
  },

  async loadPosts() {
    this.setData({ loading: true });
    
    try {
      const params = {};
      if (this.data.petTypeIndex > 0) {
        params.petType = this.data.petTypes[this.data.petTypeIndex];
      }
      if (this.data.searchText) {
        params.location = this.data.searchText;
      }

      const posts = await app.request('/posts', 'GET', params);
      this.setData({ 
        posts: posts,
        loading: false,
        noMore: posts.length === 0
      });
    } catch (error) {
      console.error('加载帖子失败:', error);
      this.setData({ loading: false });
      wx.showToast({ title: '加载失败', icon: 'none' });
    }
  },

  onPetTypeChange(e) {
    this.setData({ petTypeIndex: e.detail.value });
    this.loadPosts();
  },

  onSearchInput(e) {
    this.setData({ searchText: e.detail.value });
    clearTimeout(this.searchTimer);
    this.searchTimer = setTimeout(() => {
      this.loadPosts();
    }, 500);
  },

  onReachBottom() {
    if (!this.data.noMore && !this.data.loading) {
      this.loadMorePosts();
    }
  },

  async loadMorePosts() {
    this.setData({ loading: true });
    try {
      const params = { page: this.data.page + 1 };
      if (this.data.petTypeIndex > 0) {
        params.petType = this.data.petTypes[this.data.petTypeIndex];
      }

      const newPosts = await app.request('/posts', 'GET', params);
      if (newPosts.length > 0) {
        this.setData({
          posts: [...this.data.posts, ...newPosts],
          page: this.data.page + 1
        });
      } else {
        this.setData({ noMore: true });
      }
    } catch (error) {
      console.error('加载更多失败:', error);
    }
    this.setData({ loading: false });
  },

  onPostTap(e) {
    const postId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/post/detail/detail?id=${postId}`
    });
  },

  onCreatePost() {
    if (!app.globalData.userInfo) {
      wx.navigateTo({ url: '/pages/user/login/login' });
      return;
    }
    wx.navigateTo({ url: '/pages/post/create/create' });
  },

  formatTime(dateString) {
    const date = new Date(dateString);
    const now = new Date();
    const diff = now - date;
    const minutes = Math.floor(diff / 60000);
    const hours = Math.floor(diff / 3600000);
    const days = Math.floor(diff / 86400000);

    if (minutes < 60) {
      return `${minutes}分钟前`;
    } else if (hours < 24) {
      return `${hours}小时前`;
    } else if (days < 7) {
      return `${days}天前`;
    } else {
      return date.toLocaleDateString();
    }
  }
});